<?php

if (!defined('FT_UNKNOWN'))
    define('FT_UNKNOWN',	0);
if (!defined('FT_IMAGE'))
    define('FT_IMAGE',		1);
if (!defined('FT_TEXT'))
    define('FT_TEXT', 		2);

class Downloader {
	
	private $_curl = null;
	public $timeOut	= 3600; // 1 hour timeout (should be enough)
	public $errorId	= 0;
	public $errorMessage  = '';
	
	public function __construct() {
		$this->_curl = curl_init();
		$options = array(CURLOPT_HEADER => 0,
//				CURLOPT_FOLLOWLOCATION => 1, //disable when  in safe_mode or an open_basedir is set
				CURLOPT_FAILONERROR => 1,
                                CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.835.202 Safari/535.1',
                        );
		curl_setopt_array($this->_curl, $options);	
	}
	
	public function __destruct() {
		curl_close($this->_curl);
	}
	
        public function request($url) {
		try {
			
			$options = array(
					CURLOPT_URL => $url,					 
					CURLOPT_TIMEOUT => $this->timeOut,
                                        CURLOPT_RETURNTRANSFER => true,
                            ); 
			curl_setopt($this->_curl,CURLOPT_FAILONERROR,true);
			curl_setopt_array($this->_curl, $options);
			
			$output = curl_exec($this->_curl);
                        return $output;
		}
		catch (Exception $e){
			var_dump($e);
			$this->errorId = 0;
			$this->errorMessage = $e->getMessage;
			return false;
		}            
        }
        
	public function download($url, $savePath, $fileName, $ext = '', $fileType = FT_UNKNOWN) {
		
		if ($fileName == '' || $fileName == null) 
			$fileName = md5($url);//auto generate fileName
		
		$newFilePath = $savePath.DS.$fileName; 
		
		// ignore extension if not specifiy util retrieve file
		if (strlen($ext) > 0) 
			$newFilePath .= '.'.$ext;
        
        //auto set extension
			if ($ext == '' || $ext == null) {
				$contentType = curl_getinfo($this->_curl, CURLINFO_CONTENT_TYPE); // huypv
				$ext = $this->getFileExtension($contentType);
				
				if (strlen($ext) > 0) {
				
					$newFilePath2 = $newFilePath.'.'.$ext;
					
					if (file_exists($newFilePath2)) {
						unlink($newFilePath2);
                    }
					$newFilePath = $newFilePath2;
				}
			}
			
		try {
			$fp = fopen($newFilePath, "wb");
			
			$options = array(
					CURLOPT_URL => $url,					 
					CURLOPT_FILE => $fp,					 
					CURLOPT_TIMEOUT => $this->timeOut); 
			curl_setopt($this->_curl,CURLOPT_FAILONERROR,true);
			curl_setopt_array($this->_curl, $options);
			
			$result = curl_exec($this->_curl);

			fclose($fp);

			if ($result === false) {
				unlink($newFilePath); //remove file
				echo curl_error($this->_curl);
				return false;
			}
			
			return $newFilePath;
		}
		catch (Exception $e){
			var_dump($e);
			$this->errorId = 0;
			$this->errorMessage = $e->getMessage;
			return false;
		}
	}
	
	public function getFileExtension($contentType) {

		// What sort of image?
		$type = substr(strrchr($contentType, '/'), 1);

		switch ($type)
		{
			case 'jpg':
			case 'jpeg':
				$ext = 'jpg';break;

			case 'png':
				$ext = 'png';break;

			case 'bmp':
				$ext = 'bmp';break;

			case 'gif':
				$ext = 'gif';break;

			case 'vnd.wap.wbmp':
				$ext = 'bmp';break;

			case 'xbm':
				$ext = 'xbm';break;

			default:
				$ext = '';
		}	

		return $ext;
	}

	public function getLastError() {
		return Array(
			'code' => curl_errno($this->_curl),
			'message' => curl_error($this->_curl)
		);
	}
}